﻿using System;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using NguyenHoa.Web.App_Code;

namespace NguyenHoa.Web.Admin
{
  public partial class Introduction : AdminBasePage
  {
    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.HtmlContent;
      }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        InitPage();
        LoadContent();
      }
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      switch (para[0])
      {
        case "Save":
          e.Result = SaveContent();
          break;
        case "ChangeLanguage":
          e.Result = LoadContent();
          break;
      }
    }

    private void InitPage()
    {
      xdsLanguage.DataFile = XmlStatusFile;
      cbxLanguage.Value = CurrentLanguage.Id;
    }

    private string LoadContent()
    {
      string info = string.Empty, summary = string.Empty;
      int language = CurrentLanguage.Id;
      if (cbxLanguage.Value != null)
        int.TryParse(cbxLanguage.Value.ToString(), out language);
      HtmlContentService htmlService = new HtmlContentService();
      TList<HtmlContent> contentList = htmlService.GetByTypeAndLanguage(TypeId, language);
      HtmlContent content = null;
      if (contentList.Count > 0) content = contentList[0];
      if (content != null)
      {
        info = htmlEditor.Html = content.Content;
        summary = htmlSummary.Html = content.Summary;
      }
      return info + "|" + summary;
    }

    private string SaveContent()
    {
      try
      {
        int language = CurrentLanguage.Id;
        if (cbxLanguage.Value != null)
          int.TryParse(cbxLanguage.Value.ToString(), out language);
        HtmlContentService htmlService = new HtmlContentService();
        TList<HtmlContent> contentList = htmlService.GetByTypeAndLanguage(TypeId, language);
        HtmlContent content = null;
        if (contentList.Count > 0) content = contentList[0];
        if (content == null)
        {
          content = new HtmlContent();
          content.Name = "Menu Type: " + TypeId;
          content.CreatedDate = DateTime.Now;
          content.CreatedBy = CurrentUser.Username;
          content.LanguageId = language;
          content.TypeId = TypeId.Value;
          content.Status = NewsStatus.Approval;
        }
        content.Content = htmlEditor.Html;
        content.Summary = htmlSummary.Html;
        htmlService.Save(content);
      }
      catch (Exception ex)
      {
        WriteLog("Introductions.aspx::Save Content - Menu Type: " + TypeId, ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }
  }
}
